package com.itcast.order.controller;

import com.itcast.order.entity.Product;
import com.itcast.order.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {
    private int count = 0;
//    @Autowired
//    private RestTemplate restTemplate;

    /**
     * 注入DiscoveryClient
     * springcloud提供的获取元数据数组的工具类
     */
//    @Autowired
//    private DiscoveryClient discoveryClient;

    /**
     * 基于ribbon调用远程微服务
     * 1.使用@LoadBalanced声明RestTemplate
     * 2.使用服务名替换ip
     */

    @Autowired
    private ProductFeignClient productFeignClient;

    @GetMapping("/buy/{id}")
    public Product findById(@PathVariable Long id){
        System.out.println(++count);
//        Product product = restTemplate.getForObject("http://service-product/product/" + id, Product.class);
        Product product = productFeignClient.findById(id);
        return product;
    }

//        @GetMapping("/buy/{id}")
//    public Product findById(@PathVariable Long id){
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance serviceInstance = instances.get(0);
//        Product product = restTemplate.getForObject(
//                "http://" + serviceInstance.getHost() +
//                    ":" + serviceInstance.getPort() + "/product/" + id, Product.class);
//        return product;
//    }
}
